import { getInfo, login } from '@/services/login';
import { Button, Checkbox, Form, Input, message } from 'antd';
import React from 'react';
import { history, useModel } from 'umi';
import styles from './index.less';
import store from '@/redux/store.js'
import { setUserInfo } from '@/redux/actions'

const Login: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const onFinish = async (values: any) => {
    const hide = message.loading('登录中');
    hide();
    try {
      const response = await login({ ...values });
      if (response.status == 200) {
        message.success('登录成功');
        await fetchUserInfo();
        history.push('/index');
        return;
      } else {
        message.error('登录失败，请重试！');
      }
    } catch (error) {
      message.error('登录失败，请重试！');
    }
  };

  const fetchUserInfo = async () => {
    const userInfo = await getInfo({});
    if (userInfo) {
      store.dispatch(setUserInfo(userInfo))
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  return (
    <div>
      <div className={styles.loginBg}>
        <div className={styles.left}></div>
        <div className={styles.right}>
          <div className={styles.logoArea}></div>
          <div className={styles.preForm}>
            <Form
              name="basic"
              layout="vertical"
              labelCol={{ span: 24 }}
              wrapperCol={{ span: 24 }}
              style={{ maxWidth: 600 }}
              initialValues={{ remember: true }}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              autoComplete="off"
            >
              <Form.Item
                label="账 号"
                name="username"
                rules={[{ required: true, message: '请输入账号!' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item
                label="密 码"
                name="password"
                rules={[{ required: true, message: '请输入密码!' }]}
              >
                <Input.Password />
              </Form.Item>

              <Form.Item
                name="remember"
                valuePropName="checked"
                wrapperCol={{ offset: 0, span: 24 }}
              >
                <Checkbox>记住我</Checkbox>
              </Form.Item>

              <Form.Item wrapperCol={{ offset: 0, span: 24 }}>
                <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
                  立即登录
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;
